<?php

declare(strict_types=1);

namespace App;

use Hyperf\Context\ApplicationContext;
use Hyperf\Logger\LoggerFactory;
use App\Components\AliyunSls\Logger;
use Hyperf\Coroutine\Coroutine;

class Log
{

    /**
     * Log类.
     * @return \Psr\Log\LoggerInterface
     */
    public static function get(string $name = 'app', string $group = 'default')
    {
        return ApplicationContext::getContainer()->get(LoggerFactory::class)->get($name, $group);
    }

    /**
     * Notes: 根据当前环境保存日志，非线上往本地写日志，非本地都往阿里写日志
     * User: Ken
     * DateTime: 2024/10/12
     * @return void
     */
    public static function custom(string $message, array $context, string $group = 'custom')
    {
        Coroutine::create(function () use ($message, $context, $group) {
//            $result = [];
//            foreach ($context as $key => $item) {
//                if ($key == 'response' && isset($item['data'])) {
//                    $response_data = is_array($item['data']) ? $item['data'] : [$item['data']];
//                    unset($item['data']);
//                    $item = array_merge($item, $response_data);
//                }
//                $result[$key] = is_array($item) ? json_encode($item, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : $item;
//            }
            //非本地都往阿里写日志
            if (!isLocal()) {
                try {
                    Logger::instance()->write($message, $context);
                } catch (\Throwable $e) {
                }
            }
            //非线上往本地写日志
            if (!isProd()) {
                ApplicationContext::getContainer()->get(LoggerFactory::class)->get('app', $group)->info($message, $context);
            }
        });
    }
}
